<template>
  <div class="configuredRule">
    <el-card shadow="hover" class="card-search">
      <el-row>
        <el-col :span="20">
          <div class="search_detail">
            <div class="search">
              <span class="span_name">账户：</span>
              <el-input v-model="state.params.realName" placeholder="请输入" clearable />
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
          <el-button type="danger" :icon="Delete" @click="reast">重置</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="hover" class="card-main">
      <el-button type="primary" @click="addShop">新增商户账号</el-button>
      <el-table :data="state.tableData" stripe style="width: 100%">
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column prop="username" label="账户" width="190" />
        <el-table-column prop="mobile" label="账户类型">
          <template #default="scope">
            {{ flutter(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="300px">
          <template #default="scope">
            <el-button type="primary" size="small" @click="update(scope.row)">修改信息</el-button>
            <el-button type="primary" size="small" @click="updatePassworld(scope.row)">修改密码</el-button>
            <el-button type="danger" size="small" @click="deleteRow(scope.row)"
              v-if="scope.row.businessId !== null">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="prev, pager, next" :total="state.totalCount"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <el-dialog v-model="state.dialogVisible" title="新增账号" width="30%" :before-close="handleClose">
      <el-form-item label="账号:" :label-width="formLabelWidth">
        <el-input v-model="state.diaCity.username" style="width: 214px;" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="密码:" :label-width="formLabelWidth">
        <el-input v-model="state.diaCity.password" style="width: 214px;" show-password placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="关联门店:" :label-width="formLabelWidth">
        <el-select v-model="state.diaCity.businessId" placeholder="请选择门店">
          <el-option v-for="(item, index) in optionsMd" :key="index" :label="item.businessName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色列表:" :label-width="formLabelWidth">
        <el-select v-model="state.diaCity.roleIdList[0]" placeholder="请选择角色">
          <el-option v-for="(item, index) in state.role" :key="index" :label="item.roleName" :value="item.roleId" />
        </el-select>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveList"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="state.dialogVisibleUpdata" title="修改账号" width="30%" :before-close="handleClose">
      <el-form-item label="账号:" :label-width="formLabelWidth">
        <el-input v-model="state.diaCity.username" style="width: 214px;" placeholder="请输入"></el-input>
      </el-form-item>
      <!-- <el-form-item label="密码:" :label-width="formLabelWidth">
        <el-input v-model="state.diaCity.password" style="width: 214px;" show-password placeholder="请输入"></el-input>
      </el-form-item> -->
      <el-form-item label="关联门店:" :label-width="formLabelWidth">
        <el-select v-model="state.diaCity.businessId" placeholder="请选择门店">
          <el-option v-for="(item, index) in optionsMd" :key="index" :label="item.businessName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色列表:" :label-width="formLabelWidth">
        <el-select v-model="state.diaCity.roleIdList[0]" placeholder="请选择角色">
          <el-option v-for="(item, index) in state.role" :key="index" :label="item.roleName" :value="item.roleId" />
        </el-select>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisibleUpdata = false">取消</el-button>
          <el-button type="primary" @click="updataList"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="state.dialogVisiblePassword" title="修改密码" width="30%" :before-close="handleClose">
      <el-form-item label="旧密码:" :label-width="formLabelWidth">
        <el-input v-model="state.newPass.password" style="width: 214px;" show-password placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="新密码:" :label-width="formLabelWidth">
        <el-input v-model="state.newPass.newPassword" style="width: 214px;" show-password placeholder="请输入"></el-input>
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisiblePassword = false">取消</el-button>
          <el-button type="primary" @click="updataPass"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, getCurrentInstance, watch, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance();
const state = reactive({
  dialogVisible: false,
  dialogVisibleUpdata: false,
  dialogVisiblePassword: false,
  name: '',
  time: '',
  tableData: [],
  page: 1,
  totalCount: 0,
  params: {
    realName: '',
    startDate: '',
    endDate: '',
  },
  diaCity: {
    id: '',
    username: '',
    password: '',
    businessId: '',
    roleIdList: [],
  },
  newPass: {
    userId: '',
    password: '',
    newPassword: '',
  },
  role: []
})
const optionsMd = ref()
const getSelect = async () => {
  let role = await proxy.$api.home.roleSelect()
  state.role = role.list
  console.log('rolse', role);
  let resMd = await proxy.$api.home.list({ page: 1, limit: 1000, })
  optionsMd.value = resMd.page.list
}
const getData = async () => {
  //json对象转formdata格式
  function jsonToFormData(config) {
    const formData = new FormData();
    //循环传入的值转换formData
    Object.keys(config).forEach((key) => {
      formData.append(key, config[key]);
    })
    return formData;
  }
  let fromdata = jsonToFormData({ page: state.page, limit: 10, username: state.params.realName })
  let res = await proxy.$api.home.adminUserList(fromdata)
  state.tableData = res.page.list
  state.totalCount = res.page.totalCount
  console.log('res', res);
}
getSelect()
getData()
const search = () => {
  getData()
}
const reast = () => {
  state.params.realName = ''
  getData()
}
const handleCurrentChange = (e) => {
  state.page = e
  getData()
  console.log('eee', e);
}
const addShop = () => {
  state.dialogVisible = true

}
const update = async (e) => {
  state.dialogVisibleUpdata = true
  console.log('eee', e);
  let res = await proxy.$api.home.userInfo(e.userId)
  state.diaCity = res.user
  console.log('update', res);
}
const updatePassworld = (e) => {
  console.log('eeee', e);
  state.newPass.userId = e.userId
  state.dialogVisiblePassword = true
}
const deleteRow = (e) => {
  console.log('eeee', e);
  ElMessageBox.confirm(
    '是否删除此用户?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      proxy.$api.home.userDelete([e.userId]).then(res => {
        console.log('res', res);
        if (res) {
          ElMessage({
            type: 'success',
            message: '成功',
          })
          state.page = 1
          getData()
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })

}
const flutter = (e) => {
  if (e.businessId !== null) {
    const result = optionsMd.value.find((item) => item.id === e.businessId);
    console.log('result', result);
    return '门店管理员（' + result.businessName + ')'
  } else {
    if (e.username === 'admin') {
      return '超级管理员'
    } else {
      return '管理员'
    }

  }
}
const saveList = async () => {
  console.log('state.diaCity', state.diaCity);
  proxy.$api.home.userSave(state.diaCity).then(res => {
    console.log('res', res);
    console.log('state.diaCity', state.diaCity);
    getData()
    ElMessage({
      type: 'success',
      message: '保存成功',
    })
    state.dialogVisible = false
  })
}
const updataList = async () => {
  console.log('state.diaCity', state.diaCity);
  // delete state.diaCity.passworld;
  proxy.$api.home.userUpdate(state.diaCity).then(res => {
    console.log('res', res);
    console.log('state.diaCity', state.diaCity);
    if (res.code !== 500) {
      getData()
      ElMessage({
        type: 'success',
        message: '修改成功',
      })
      state.dialogVisibleUpdata = false
    }

  })
}
const updataPass = () => {
  function jsonToFormData(config) {
    const formData = new FormData();
    //循环传入的值转换formData
    Object.keys(config).forEach((key) => {
      formData.append(key, config[key]);
    })
    return formData;
  }
  let fromdata = jsonToFormData(state.newPass)
  console.log('ssss', state.newPass);
  if (state.newPass.password === '') {
    ElMessage({
      type: 'error',
      message: '请填写旧密码',
    })
  } else if (state.newPass.newPassword === '') {
    ElMessage({
      type: 'error',
      message: '请填写新密码',
    })
  } else {

    proxy.$api.home.password(fromdata).then((res) => {
      if (res.code !== 500) {
        state.dialogVisiblePassword = false
        ElMessage({
          type: 'success',
          message: 'ok',
        })
      }
    })
  }

}
watch(
  () => state.dialogVisible,
  (n) => {
    if (n == false) {
      state.diaCity = {
        id: '',
        username: '',
        password: '',
        businessId: '',
        roleIdList: [],
      },
        console.log('n', n);
    }

  }
)
watch(
  () => state.dialogVisibleUpdata,
  (n) => {
    if (n == false) {
      state.diaCity = {
        id: '',
        username: '',
        password: '',
        businessId: '',
        roleIdList: [],
      },
        console.log('n', n);
    }

  }
)
watch(
  () => state.dialogVisiblePassword,
  (n) => {
    if (n == false) {
      state.newPass = {
        password: '',
        newPassword: '',
      }
    }
  }
)
</script>

<style lang="scss" scoped>
.configuredRule {
  padding: 20px;

  .search_detail {
    display: flex;

    .search {
      margin-right: 10px;
      display: flex;
      align-items: center;

      .span_name {
        width: 110px;
        font-size: 16px;
      }
    }
  }

  .card-main {
    margin-top: 20px;
    height: calc(100vh - 200px);
    position: relative;

    .pagination {
      margin-top: 10px;
      display: flex;
      justify-content: flex-end;
      text-align: right;
    }
  }
}

.inputa {
  .searcha {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .span_name {
      width: 130px;
      font-size: 16px;
    }
  }
}
</style>